package com.timeshare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.timeshare.dto.ChatMessageDTO;
import com.timeshare.entity.ChatMessage;
import com.timeshare.mapper.ChatMessageMapper;
import com.timeshare.service.ChatService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 聊天服务实现
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatService {
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChatMessage saveMessage(ChatMessageDTO messageDTO) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSenderId(messageDTO.getSenderId());
        chatMessage.setReceiverId(messageDTO.getReceiverId());
        chatMessage.setMessageType(messageDTO.getMessageType() != null ? messageDTO.getMessageType() : 1);
        chatMessage.setContent(messageDTO.getContent());
        chatMessage.setIsRead(0);
        
        this.save(chatMessage);
        return chatMessage;
    }
    
    @Override
    public List<ChatMessage> getChatHistory(Long userId1, Long userId2, Integer limit) {
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w
                .and(w1 -> w1.eq(ChatMessage::getSenderId, userId1).eq(ChatMessage::getReceiverId, userId2))
                .or(w2 -> w2.eq(ChatMessage::getSenderId, userId2).eq(ChatMessage::getReceiverId, userId1))
        );
        wrapper.orderByDesc(ChatMessage::getCreateTime);
        wrapper.last("LIMIT " + limit);
        
        return this.list(wrapper);
    }
    
    @Override
    public Integer getUnreadCount(Long userId) {
        LambdaQueryWrapper<ChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatMessage::getReceiverId, userId)
               .eq(ChatMessage::getIsRead, 0);
        return Math.toIntExact(this.count(wrapper));
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markAsRead(Long userId, Long senderId) {
        LambdaUpdateWrapper<ChatMessage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChatMessage::getReceiverId, userId)
               .eq(ChatMessage::getSenderId, senderId)
               .eq(ChatMessage::getIsRead, 0)
               .set(ChatMessage::getIsRead, 1);
        this.update(wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recallMessage(Long messageId, Long userId) {
        ChatMessage message = this.getById(messageId);
        if (message == null) {
            throw new RuntimeException("消息不存在");
        }
        
        // 只能撤回自己发送的消息
        if (!message.getSenderId().equals(userId)) {
            throw new RuntimeException("只能撤回自己的消息");
        }
        
        // 只能撤回2分钟内的消息
        long minutes = java.time.Duration.between(message.getCreateTime(), java.time.LocalDateTime.now()).toMinutes();
        if (minutes > 2) {
            throw new RuntimeException("只能撤回2分钟内的消息");
        }
        
        // 标记为已撤回
        message.setRecalled(1);
        this.updateById(message);
    }
}

